//用户管理的 路由
//1、引入express框架
const express = require("express");//第2此加载模块的缓存
const db = require("../modules/DBhelper");
//2、聘请保安 (创建)
const moment = require("moment");
let router = express.Router();

router.get('checkname',async (request,response,next)=>{
    try {
        let sql='SELECT*FROM userinfo WHERE u_phone=?  ;'
        let result=await db.exec(sql,[request.query.uphone]);
        let isCheckName=!(result&&result.length>=1);
        response.end(isCheckName+'');
    } catch (error) {
        response.end('false');
    }
})

router.post("/login", async function (request, response, next) {
    let userObj = request.body;
    let sql = "select *from `userinfo`where u_name=? And u_pwd = ?; ";
    let params = [
        userObj.uname,
        userObj.upwd,
    ];
    let result = await db.exec(sql, params);
    let isLogin = result && result.length >= 1;
    if (isLogin) {
        delete (result[0].u_pwd);//这个字段来自数据库
    }
    let messages = {
        msg: isLogin ? "登录成功" : "登录失败",
        data: isLogin ? result : '',
        status: isLogin ? 200 : -200
    }
    response.json(messages);
})

router.post("/reg", async function (request, response, next) {
    //1、得到前端传过来的数据
    let userObj = request.body;
    let sql = "INSERT INTO `userinfo`(`u_name`,`u_pwd`,`u_phone`,`u_createtime`)VALUE(?,?,?,?)";
    let params = [
        userObj.uname,
        userObj.upwd,
        userObj.uphone,
        moment().format("YYYY-MM-DD HH:mm:ss")
    ];
    let result = await db.exec(sql, params);
    let isReg = result && result.affectedRows;
    let messages = {
        msg: isReg ? "注册成功" : "注册失败",
        status: isReg ? 200 : -200,
    }
    response.json(messages);
})

//暴露
module.exports = {
    router
}

//http//127.0.0.1:8080/account/login
//http//127.0.0.1:8080/account/reg